package network;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class SingleChatServer extends JFrame implements Runnable{

	ServerSocket server = null;
	Socket client = null;
	
	boolean threadFlag = true;
	int portNum = 4444;
	
	StringBuilder data = new StringBuilder();
	BufferedReader receive = null;
	BufferedWriter send = null;
	
	private JPanel contentPane;
	private JPanel panel;
	private JPanel panel_1;
	private JButton serStart;
	private JButton serStop;
	private JTextField message;
	private JButton btnNewButton_2;
	private JScrollPane scrollPane;
	private JTextPane result;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SingleChatServer frame = new SingleChatServer();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public SingleChatServer() {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent arg0) {
				serverStop();
			}
		});
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 500, 500);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getPanel_1(), BorderLayout.SOUTH);
		contentPane.add(getScrollPane(), BorderLayout.CENTER);
		
		try {
			InetAddress ia = InetAddress.getLocalHost();
			setTitle("서버 IP: "+ia.getHostAddress()+" / port : "+portNum);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
	}
	
	public void sendMsg(String ms){
		try{
			send.write(ms);
			send.newLine();
			send.flush();
			dataSet("<font color = 'blue'> 서버 :"+ms+"</font>");
		} catch (Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void serverStart(){
		try{
		
		Thread t = new Thread(this);//액션안에 있는게 아니기에 그냥 this만 사용해도 된다.
		t.start();

		serStart.setEnabled(false);
		serStop.setEnabled(true);
		
		dataSet("<b>서버가 시작 되었습니다.</b>");		
		
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void serverStop(){
		serStart.setEnabled(true);
		serStop.setEnabled(false);
		threadFlag = false;
		try {
			send.write("\tserverdown");
			send.newLine();
			send.flush();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	public void dataSet(String d){//JTextPane에 문자열을 추가하기 위해서
		data.append(d);//StringBuilder에 String을 추가
		data.append("<br/>");
		result.setText(data.toString());
	}

	@Override
	public void run() {
		
		try{
		server = new ServerSocket(portNum);
		client = server.accept();//소켓으로 반환

		OutputStream os = client.getOutputStream();
		OutputStreamWriter osw = new OutputStreamWriter(os);
		send = new BufferedWriter(osw);
		
		InputStream is = client.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		receive = new BufferedReader(isr);

		threadFlag = true;
		
     		while (threadFlag) {
				String str = receive.readLine();
//				if ("\tserverdown".equals(str)) {
//					threadFlag = false;
//					break;
//				} else if ("\tkill".equals(str)) {
//					threadFlag = false;
//					break;
//				} else {
					dataSet("수신 : " + str);
//					
//				}
			}
		
		dataSet("<font color = 'red' > 서버가 중지되었습니다 </font>");
		serStart.setEnabled(true);
		serStop.setEnabled(false);
		
		receive.close();
		isr.close();
		is.close();
		
		send.close();
		osw.close();
		os.close();
		
		client.close();
		server.close();
		
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getSerStart(), BorderLayout.WEST);
			panel.add(getSerStop(), BorderLayout.EAST);
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getMessage(), BorderLayout.CENTER);
			panel_1.add(getBtnNewButton_2(), BorderLayout.EAST);
		}
		return panel_1;
	}
	private JButton getSerStart() {
		if (serStart == null) {
			serStart = new JButton("서버시작");
			serStart.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					serverStart();
				}
			});
		}
		return serStart;
	}
	private JButton getSerStop() {
		if (serStop == null) {
			serStop = new JButton("서버종료");
			serStop.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					serverStop();
				}
			});
		}
		return serStop;
	}
	private JTextField getMessage() {
		if (message == null) {
			message = new JTextField();
			message.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					if(e.getKeyCode()==KeyEvent.VK_ENTER){
						String str = message.getText();
						sendMsg(str);
						message.setText("");
					}else if(e.getKeyCode()==KeyEvent.VK_ESCAPE){
						message.setText("");
					}
				}
			});
			message.setColumns(10);
		}
		return message;
	}
	private JButton getBtnNewButton_2() {
		if (btnNewButton_2 == null) {
			btnNewButton_2 = new JButton("메시지 전송");
			btnNewButton_2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					String str = message.getText();
					sendMsg(str);
					message.setText("");
				}
			});
		}
		return btnNewButton_2;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}
	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setContentType("text/html");
		}
		return result;
	}
}
